package com.hjimi.ski.utils;

import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.hjimi.ski.config.UrlConfig;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

/**
 * Created By 孙岩
 * on 2023/11/16
 */
public class NetworkPostTask extends AsyncTask<String, Void, String> {
    private Handler mHandler;

    public NetworkPostTask(Handler handler) {
        this.mHandler = handler;
    }
    @Override
    protected String doInBackground(String... params) {
        try {
//            URL url = new URL("https://ishow.aiyuechen.com/api/screen/client/v1/init");
            URL url = new URL(UrlConfig.baseUrl +"/api/screen/client/v1/init");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setConnectTimeout(5000);


            conn.setDoOutput(true);
            Log.d("sunyan","参数==="+params[0]);
            byte[] postDataBytes = params[0].getBytes(StandardCharsets.UTF_8);

            OutputStream outputStream = conn.getOutputStream();
            outputStream.write(postDataBytes);
            outputStream.flush();
            outputStream.close();

            int responseCode = conn.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                InputStream inputStream = conn.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
                String line;
                StringBuilder response = new StringBuilder();
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                return response.toString();
            } else {
                return "Error: " + responseCode;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return "Error: " + e.getMessage();
        }
    }

    @Override
    protected void onPostExecute(String result) {
        // 在这里处理网络请求结果，更新UI等操作
        Message message = Message.obtain();
        message.what = 1; // 设置消息标识符为0
        message.obj =  result; // 设置消息对象为"你好"字符串
        mHandler.sendMessage(message); // 发送消息到主线程
    }
}
